/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pp.persistance;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.pp.entites.Rack;
import com.pp.entites.Traitement;
import com.pp.entites.Tube;
import com.pp.persistance.exceptions.NonexistentEntityException;
import com.pp.persistance.exceptions.PreexistingEntityException;
import com.pp.persistance.exceptions.RollbackFailureException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author arnaud
 */
public class TubeJpaController implements Serializable {

    public TubeJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Tube tube) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (tube.getTraitementList() == null) {
            tube.setTraitementList(new ArrayList<Traitement>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Rack idrack = tube.getIdrack();
            if (idrack != null) {
                idrack = em.getReference(idrack.getClass(), idrack.getId());
                tube.setIdrack(idrack);
            }
            List<Traitement> attachedTraitementList = new ArrayList<Traitement>();
            for (Traitement traitementListTraitementToAttach : tube.getTraitementList()) {
                traitementListTraitementToAttach = em.getReference(traitementListTraitementToAttach.getClass(), traitementListTraitementToAttach.getId());
                attachedTraitementList.add(traitementListTraitementToAttach);
            }
            tube.setTraitementList(attachedTraitementList);
            em.persist(tube);
            if (idrack != null) {
                idrack.getTubeList().add(tube);
                idrack = em.merge(idrack);
            }
            for (Traitement traitementListTraitement : tube.getTraitementList()) {
                traitementListTraitement.getTubeList().add(tube);
                traitementListTraitement = em.merge(traitementListTraitement);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findTube(tube.getId()) != null) {
                throw new PreexistingEntityException("Tube " + tube + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Tube tube) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Tube persistentTube = em.find(Tube.class, tube.getId());
            Rack idrackOld = persistentTube.getIdrack();
            Rack idrackNew = tube.getIdrack();
            List<Traitement> traitementListOld = persistentTube.getTraitementList();
            List<Traitement> traitementListNew = tube.getTraitementList();
            if (idrackNew != null) {
                idrackNew = em.getReference(idrackNew.getClass(), idrackNew.getId());
                tube.setIdrack(idrackNew);
            }
            List<Traitement> attachedTraitementListNew = new ArrayList<Traitement>();
            for (Traitement traitementListNewTraitementToAttach : traitementListNew) {
                traitementListNewTraitementToAttach = em.getReference(traitementListNewTraitementToAttach.getClass(), traitementListNewTraitementToAttach.getId());
                attachedTraitementListNew.add(traitementListNewTraitementToAttach);
            }
            traitementListNew = attachedTraitementListNew;
            tube.setTraitementList(traitementListNew);
            tube = em.merge(tube);
            if (idrackOld != null && !idrackOld.equals(idrackNew)) {
                idrackOld.getTubeList().remove(tube);
                idrackOld = em.merge(idrackOld);
            }
            if (idrackNew != null && !idrackNew.equals(idrackOld)) {
                idrackNew.getTubeList().add(tube);
                idrackNew = em.merge(idrackNew);
            }
            for (Traitement traitementListOldTraitement : traitementListOld) {
                if (!traitementListNew.contains(traitementListOldTraitement)) {
                    traitementListOldTraitement.getTubeList().remove(tube);
                    traitementListOldTraitement = em.merge(traitementListOldTraitement);
                }
            }
            for (Traitement traitementListNewTraitement : traitementListNew) {
                if (!traitementListOld.contains(traitementListNewTraitement)) {
                    traitementListNewTraitement.getTubeList().add(tube);
                    traitementListNewTraitement = em.merge(traitementListNewTraitement);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = tube.getId();
                if (findTube(id) == null) {
                    throw new NonexistentEntityException("The tube with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Tube tube;
            try {
                tube = em.getReference(Tube.class, id);
                tube.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The tube with id " + id + " no longer exists.", enfe);
            }
            Rack idrack = tube.getIdrack();
            if (idrack != null) {
                idrack.getTubeList().remove(tube);
                idrack = em.merge(idrack);
            }
            List<Traitement> traitementList = tube.getTraitementList();
            for (Traitement traitementListTraitement : traitementList) {
                traitementListTraitement.getTubeList().remove(tube);
                traitementListTraitement = em.merge(traitementListTraitement);
            }
            em.remove(tube);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Tube> findTubeEntities() {
        return findTubeEntities(true, -1, -1);
    }

    public List<Tube> findTubeEntities(int maxResults, int firstResult) {
        return findTubeEntities(false, maxResults, firstResult);
    }

    private List<Tube> findTubeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Tube.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Tube findTube(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Tube.class, id);
        } finally {
            em.close();
        }
    }

    public int getTubeCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Tube> rt = cq.from(Tube.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
